<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'

const props = defineProps({
  images: {
    type: Array,
    required: true,
    validator: value => value.length > 0
  },
  interval: {
    type: Number,
    default: 5000
  }
})

const currentIndex = ref(0)
let timer = null

const startCarousel = () => {
  timer = setInterval(() => {
    currentIndex.value = (currentIndex.value + 1) % props.images.length
  }, props.interval)
}

onMounted(startCarousel)
onBeforeUnmount(() => clearInterval(timer))
</script>

<template>
  <div class="carousel-container">
    <!-- 轮播背景 -->
    <div v-for="(image, index) in images" :key="index" class="carousel-item" :style="{ backgroundImage: `url(${image})`, opacity: currentIndex === index ? 1 : 0 }"></div>

    <!-- 内容插槽 -->
    <div class="content-slot">
      <slot></slot>
    </div>
  </div>
</template>

<style scoped>
.carousel-container {
  position: relative;
  width: 100%;
  height: 400px;
  overflow: hidden;
}

.carousel-item {
  position: absolute;
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  transition: opacity 1s ease-in-out;
}

.content-slot {
  position: relative;
  z-index: 1;
  width: 100%;
  height: 100%;
  pointer-events: none; /* 允许穿透点击 */
}

.content-slot ::v-slotted(*) {
  pointer-events: auto; /* 恢复插槽内容点击 */
}
</style>